const http = require('http');

function makeRequest(options, data = null) {
    return new Promise((resolve, reject) => {
        const req = http.request(options, (res) => {
            let body = '';
            res.on('data', (chunk) => body += chunk);
            res.on('end', () => {
                try {
                    const jsonBody = body ? JSON.parse(body) : {};
                    resolve({ status: res.statusCode, data: jsonBody, body });
                } catch (e) {
                    resolve({ status: res.statusCode, data: null, body });
                }
            });
        });

        req.on('error', reject);
        
        if (data) {
            req.write(data);
        }
        
        req.end();
    });
}

async function testAPI() {
    console.log('🧪 测试API功能...');
    
    const baseOptions = {
        hostname: 'localhost',
        port: 3000,
        headers: {
            'Content-Type': 'application/json'
        }
    };

    try {
        // 1. 健康检查
        console.log('\n1️⃣ 测试健康检查...');
        const healthResult = await makeRequest({
            ...baseOptions,
            path: '/health',
            method: 'GET'
        });
        
        if (healthResult.status === 200) {
            console.log('✅ 服务器运行正常:', healthResult.data.message);
        } else {
            console.log('❌ 健康检查失败:', healthResult.status);
        }

        // 2. 获取歌曲列表
        console.log('\n2️⃣ 测试获取歌曲列表...');
        const songsResult = await makeRequest({
            ...baseOptions,
            path: '/api/songs',
            method: 'GET'
        });
        
        if (songsResult.status === 200 && songsResult.data.success) {
            console.log(`✅ 获取到${songsResult.data.data.length}首歌曲`);
            songsResult.data.data.slice(0, 3).forEach((song, index) => {
                console.log(`  ${index + 1}. ${song.title} - ${song.artist}`);
            });
        } else {
            console.log('❌ 获取歌曲列表失败:', songsResult.data);
        }

        // 3. 获取歌手列表
        console.log('\n3️⃣ 测试获取歌手列表...');
        const singersResult = await makeRequest({
            ...baseOptions,
            path: '/api/songers',
            method: 'GET'
        });
        
        if (singersResult.status === 200 && singersResult.data.success) {
            console.log(`✅ 获取到${singersResult.data.data.length}位歌手`);
            singersResult.data.data.slice(0, 3).forEach((singer, index) => {
                console.log(`  ${index + 1}. ${singer.name}`);
            });
        } else {
            console.log('❌ 获取歌手列表失败:', singersResult.data);
        }

        // 4. 测试添加歌手
        console.log('\n4️⃣ 测试添加歌手...');
        const newSingerName = '测试歌手API-' + Date.now();
        const addSingerResult = await makeRequest({
            ...baseOptions,
            path: '/api/songers',
            method: 'POST'
        }, JSON.stringify({ name: newSingerName }));
        
        if (addSingerResult.status === 200 && addSingerResult.data.success) {
            console.log('✅ 歌手添加成功:', addSingerResult.data.data);
        } else {
            console.log('❌ 歌手添加失败:', addSingerResult.data);
        }

        // 5. 测试添加歌曲
        console.log('\n5️⃣ 测试添加歌曲...');
        const newSongName = '测试歌曲API-' + Date.now();
        const addSongResult = await makeRequest({
            ...baseOptions,
            path: '/api/songs',
            method: 'POST'
        }, JSON.stringify({ name: newSongName }));
        
        if (addSongResult.status === 200 && addSongResult.data.success) {
            console.log('✅ 歌曲添加成功:', addSongResult.data.data);
        } else {
            console.log('❌ 歌曲添加失败:', addSongResult.data);
        }

        console.log('\n🎉 API测试完成！');
        
        // 6. 再次检查数据库
        console.log('\n6️⃣ 验证数据库更新...');
        const finalSongsResult = await makeRequest({
            ...baseOptions,
            path: '/api/songs',
            method: 'GET'
        });
        
        const finalSingersResult = await makeRequest({
            ...baseOptions,
            path: '/api/songers',
            method: 'GET'
        });
        
        console.log(`📊 最终统计:`);
        console.log(`  - 歌曲总数: ${finalSongsResult.data.data.length}`);
        console.log(`  - 歌手总数: ${finalSingersResult.data.data.length}`);

    } catch (error) {
        if (error.code === 'ECONNREFUSED') {
            console.log('❌ 无法连接到服务器，请确保服务器正在运行');
        } else {
            console.error('❌ 测试失败:', error.message);
        }
    }
}

testAPI().then(() => {
    console.log('\n🏁 测试完成');
    process.exit(0);
}).catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
});